<template>
  <div class="loan-management">
    <el-form ref="searchFormRef">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="贷款产品">
            <el-input
              v-model="searchForm.productName"
              placeholder="请输入贷款产品搜索"
              @keyup.enter="handleSearch"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="客户名称">
            <el-input
              v-model="searchForm.customerName"
              placeholder="请输入客户名称搜索"
              @keyup.enter="handleSearch"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="贷款状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择贷款状态"
              @change="handleSearch"
              clearable
            >
              <el-option
                v-for="(item, index) in statusTypeMap"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <template v-if="showMoreSearch">
          <el-col :span="6">
            <el-form-item label="客户经理">
              <el-input
                v-model="searchForm.collectionManager"
                placeholder="请输入客户经理搜索"
                @keyup.enter="handleSearch"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="催收状态">
              <el-select
                v-model="searchForm.collectionStatus"
                placeholder="请选择催收状态"
                @change="handleSearch"
                clearable
              >
                <el-option
                  v-for="(item, index) in collectionStatusTypeMap"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="6">
          <el-button color="#19af7d" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button
            @click="showMoreSearch = !showMoreSearch"
            type="primary"
            link
            :icon="getMoreSearchIcon()"
          >
            {{ showMoreSearch ? "收起" : "更多" }}
          </el-button>
        </el-col>
      </el-row>
    </el-form>

    <el-button color="#19af7d" @click="addForm" style="margin-bottom: 20px"
      >新增贷款</el-button
    >

    <el-table :data="dataList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="customerName" label="客户名称" align="center" />
      <el-table-column prop="productName" label="贷款产品" align="center" />
      <el-table-column prop="loanAmount" label="贷款金额" align="center">
        <template #default="scope">
          {{ formatAmount(scope.row.loanAmount) || "0元" }}
        </template>
      </el-table-column>
      <el-table-column prop="unpaidAmount" label="未还金额" align="center">
        <template #default="scope">
          {{ formatAmount(scope.row.unpaidAmount) || "0元" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="startTime"
        label="贷款开始日期"
        width="180"
        align="center"
      />
      <el-table-column
        prop="endTime"
        label="贷款结束日期"
        width="180"
        align="center"
      />
      <el-table-column prop="status" label="贷款状态" align="center">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="overdueDays" label="逾期天数" align="center">
        <template #default="scope">
          <span :style="{ color: scope.row.overdueDays > 0 ? 'red' : '' }">
            {{ scope.row.overdueDays }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="unpaidInterest" label="欠息金额" align="center">
        <template #default="scope">
          {{ formatAmount(scope.row.unpaidInterest) || "0元" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="collectionManager"
        label="客户经理"
        align="center"
      ></el-table-column>
      <el-table-column prop="collectionStatus" label="催收状态" align="center">
        <template #default="scope">
          <el-tag :type="getCollectionStatusType(scope.row.collectionStatus)">
            {{ scope.row.collectionStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button size="small" @click="editForm(scope.row)">
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <Pagination v-model="currentPage" :page-size="pageSize" :total="total" />

    <Form
      v-model="dialogVisible"
      :isEdit="isEdit"
      :formData="loanForm"
      @save="handleSave"
    />
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowUp, ArrowDown } from "@element-plus/icons-vue";
import Pagination from "@/components/Pagination.vue";
import Form from "./form.vue";

// 获取路由实例
const route = useRoute();
// 初始化 type，默认为 all，从路由获取值
const type = ref(route.query.type || "all");


// 所有贷款数据
const allData = ref([
  {
    id: 1,
    productName: "个人信用",
    customerName: "张三",
    loanAmount: 100000,
    unpaidAmount: 80000,
    startTime: "2023-01-01",
    endTime: "2025-01-01",
    status: "还款中",
    overdueDays: 0,
    unpaidInterest: 0,
    collectionManager: "张三",
    collectionStatus: "未催收",

  },
  {
    id: 2,
    productName: "房屋抵押",
    customerName: "李四",
    loanAmount: 500000,
    unpaidAmount: 450000,
    startTime: "2023-01-02",
    endTime: "2025-07-05",
    status: "已逾期",
    overdueDays: 15,
    unpaidInterest: 2000,
    collectionManager: "张三",
    collectionStatus: "未催收",

  },
  {
    id: 3,
    productName: "车辆抵押",
    customerName: "王五",
    loanAmount: 200000,
    unpaidAmount: 180000,
    startTime: "2023-01-03",
    endTime: "2033-01-03",
    status: "已完成",
    overdueDays: 0,
    unpaidInterest: 0,
    collectionManager: "张三",
    collectionStatus: "已催收",

  },
]);

// 将搜索字段合并到一个对象中
const searchForm = ref({
  productName: "",
  customerName: "",
  status: "",
  collectionManager: "",
  collectionStatus: "",
});

// 当前页码
const currentPage = ref(1);
// 分页数量
const pageSize = ref(10);
// 是否显示更多搜索项
const showMoreSearch = ref(false);
// 更多搜索图标
const getMoreSearchIcon = () => {
  return showMoreSearch.value ? ArrowUp : ArrowDown;
};

// 贷款状态类型映射
const statusTypeMap = [
  { label: "还款中", value: "还款中", type: "primary" },
  { label: "已逾期", value: "已逾期", type: "danger" },
  { label: "已完成", value: "已完成", type: "success" },
  { label: "未知状态", value: "", type: "info" }, // 处理空值情况
];

// 催收状态类型映射
const collectionStatusTypeMap = [
  { label: "未催收", value: "未催收", type: "info" },
  { label: "已催收", value: "已催收", type: "success" },
];

// 获取贷款状态类型
const getStatusType = (status) => {
  const found = statusTypeMap.find((item) => item.value === status);
  return found?.type || "info"; // 确保不会返回空字符串
};

// 获取催收状态类型
const getCollectionStatusType = (collectionStatus) => {
  const found = collectionStatusTypeMap.find(
    (item) => item.value === collectionStatus
  );
  return found?.type || "info"; // 确保不会返回空字符串
};

// 金额格式化函数
const formatAmount = (amount) => {
  return `${amount.toFixed(2)} 元`;
};

// 根据搜索过滤贷款数据
const filteredData = computed(() => {
  return allData.value.filter((item) => {
    const productMatch = item.productName
      .toLowerCase()
      .includes(searchForm.value.productName.toLowerCase());
    const customerMatch = item.customerName
      .toLowerCase()
      .includes(searchForm.value.customerName.toLowerCase());
    // 当未选择状态时，不过滤状态
    const statusMatch =
      !searchForm.value.status || item.status === searchForm.value.status;
    const managerMatch =
      !searchForm.value.collectionManager ||
      item.collectionManager
        ?.toLowerCase()
        .includes(searchForm.value.collectionManager.toLowerCase());
    const collectionStatusMatch =
      !searchForm.value.collectionStatus ||
      item.collectionStatus === searchForm.value.collectionStatus;
    return (
      productMatch &&
      customerMatch &&
      statusMatch &&
      managerMatch &&
      collectionStatusMatch
    );
  });
});

// 根据当前页码和每页显示数量，计算当前页要显示的贷款数据
const dataList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredData.value.slice(start, end);
});

// 计算过滤后总条数
const total = computed(() => filteredData.value.length);

const dialogVisible = ref(false);
const isEdit = ref(false);
// 贷款表单数据，添加 customerName 字段
const loanForm = ref({
  id: null,
  productName: "",
  customerName: "",
  loanAmount: 0,
  unpaidAmount: 0,
  startTime: "",
  endTime: "",
  status: "",
  overdueDays: 0,
  unpaidInterest: 0,
});

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
};

// 重置搜索条件
const handleReset = () => {
  searchForm.value = {
    productName: "",
    customerName: "",
    status: "",
    collectionManager: "",
    collectionStatus: "",
  };
  currentPage.value = 1;
};

const addForm = () => {
  isEdit.value = false;
  loanForm.value = {
    id: null,
    productName: "",
    customerName: "",
    loanAmount: 0,
    unpaidAmount: 0,
    startTime: "",
    endTime: "",
    status: "",
    overdueDays: 0,
    unpaidInterest: 0,
  };
  dialogVisible.value = true;
};

const editForm = (row) => {
  isEdit.value = true;
  loanForm.value = { ...row };
  dialogVisible.value = true;
};

const generateId = () => {
  return Math.max(...allData.value.map((item) => item.id), 0) + 1;
};

const handleSave = (data) => {
  dialogVisible.value = false;
  if (isEdit.value) {
    const index = allData.value.findIndex((item) => item.id === data.id);
    if (index !== -1) {
      // 使用浅拷贝更新数据，保证响应式
      allData.value = [
        ...allData.value.slice(0, index),
        data,
        ...allData.value.slice(index + 1),
      ];
    }
  } else {
    const newLoan = {
      ...data,
      id: generateId(),
    };
    // 使用浅拷贝添加新数据
    allData.value = [...allData.value, newLoan];
  }
  currentPage.value = 1;
  ElMessage.success(isEdit.value ? "编辑贷款成功" : "新增贷款记成功");
};

// 删除贷款
const handleDelete = (id) => {
  ElMessageBox.confirm("确定要删除该贷款吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      allData.value = allData.value.filter((item) => item.id !== id);
      ElMessage.success("删除贷款成功");
      if (dataList.value.length === 0 && currentPage.value > 1) {
        currentPage.value--;
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};
</script>

<style scoped lang="scss">
@use "./index.scss";
</style>
